package com.huahua.bigdata.spark.rdd.operate;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

public class Spark11_Operate_Transform_KV_groupByKey {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf();
        conf.setMaster("local");
        conf.setAppName("spark");
        JavaSparkContext jsc = new JavaSparkContext(conf);
        /* JavaRDD<Tuple2<String, Integer>> rdd = jsc.parallelize(
                Arrays.asList(
                        new Tuple2<>("a", 1),
                        new Tuple2<>("b", 2),
                        new Tuple2<>("a", 3),
                        new Tuple2<>("b", 4)
                )
        );
        JavaPairRDD<String, Iterable<Tuple2<String, Integer>>> groupByRDD = rdd.groupBy(
                t -> t._1
        );
        groupByRDD.collect().forEach(System.out::println);
        */

        JavaPairRDD<String, Integer> pairRDD = jsc.parallelizePairs(
                Arrays.asList(
                        new Tuple2<>("a", 1),
                        new Tuple2<>("b", 2),
                        new Tuple2<>("a", 3),
                        new Tuple2<>("b", 4)
                )
        );
        // TODO groupByKey方法作用将KV类型的数据直接按照K进行分组
        pairRDD.groupByKey().collect().forEach(System.out::println);

        jsc.close();
    }
}
